package com.chushouya.order.rabbitmq.sender;

import com.chushouya.common.constant.PlatformTypeEnum;
import com.chushouya.common.util.RabbitMQUtil;
import com.chushouya.manager.service.common.ConfigApiService;
import com.chushouya.order.constants.OrderTypeEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.common.constant.RabbitMqQueueEnum;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.google.common.base.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 支付宝流程消息发送器
 * 用于发送支付宝订单流程处理消息
 * 
 * @author chushouya
 */
@Component
@Slf4j
public class AlipayFlowMessageSender {

    @Resource
    private RabbitMQUtil rabbitMQUtil;

    @Resource
    private ConfigApiService configApiService;

    /**
     * 发送支付宝流程处理消息（立即发送）
     * 
     * @param orderEntity 订单实体
     */
    public void sendAlipayFlowMessage(OrderEntity orderEntity) {
        try {
            // 验证订单实体
            validateOrderEntity(orderEntity);

            log.info("发送支付宝流程处理消息，订单ID: {}, 订单号: {}, 渠道: {}, 支付宝订单号: {}",
                    orderEntity.getOrderId(), orderEntity.getOrderNo(),
                    orderEntity.getChannel(), orderEntity.getOrderCenterNo());

            rabbitMQUtil.sendMessage(RabbitMqQueueEnum.ALIPAY_FLOW.getQueueName(), orderEntity.getOrderId());
            log.info("支付宝流程处理消息发送成功，订单ID: {}", orderEntity.getOrderId());
        } catch (Exception e) {
            log.error("发送支付宝流程处理消息异常，订单ID: {}, 错误信息: {}",
                    orderEntity.getOrderId(), e.getMessage());
        }
    }

    /**
     * 发送支付宝流程处理消息（延时发送 - 秒）
     * 
     * @param orderEntity 订单实体
     * @param delaySeconds 延时秒数
     */
    public void sendAlipayFlowMessage(OrderEntity orderEntity, int delaySeconds) {
        try {
            // 验证订单实体
            validateOrderEntity(orderEntity);
            
            log.info("发送支付宝流程处理延时消息，订单ID: {}, 延时: {}秒, 渠道: {}, 支付宝订单号: {}", 
                    orderEntity.getOrderId(), delaySeconds, orderEntity.getChannel(), orderEntity.getOrderCenterNo());
            
            rabbitMQUtil.sendDelayMessage(
                RabbitMqQueueEnum.ALIPAY_FLOW.getQueueName(), 
                orderEntity.getOrderId(), 
                delaySeconds, 
                TimeUnit.SECONDS
            );
            log.info("支付宝流程处理延时消息发送成功，订单ID: {}, 延时: {}秒", orderEntity.getOrderId(), delaySeconds);
        } catch (Exception e) {
            log.error("发送支付宝流程处理延时消息异常，订单ID: {}, 延时: {}秒, 错误信息: {}", 
                    orderEntity != null ? orderEntity.getOrderId() : "null", delaySeconds, e.getMessage(), e);
        }
    }

    /**
     * 发送支付宝流程处理消息（延时分钟）
     * 
     * @param orderEntity 订单实体
     * @param delayMinutes 延时分钟数
     */
    public void sendAlipayFlowMessageDelayMinutes(OrderEntity orderEntity, int delayMinutes) {
        try {
            // 验证订单实体
            validateOrderEntity(orderEntity);
            
            log.info("发送支付宝流程处理延时消息，订单ID: {}, 延时: {}分钟, 渠道: {}, 支付宝订单号: {}", 
                    orderEntity.getOrderId(), delayMinutes, orderEntity.getChannel(), orderEntity.getOrderCenterNo());
            
            rabbitMQUtil.sendDelayMessage(
                RabbitMqQueueEnum.ALIPAY_FLOW.getQueueName(), 
                orderEntity.getOrderId(), 
                delayMinutes, 
                TimeUnit.MINUTES
            );
            log.info("支付宝流程处理延时消息发送成功，订单ID: {}, 延时: {}分钟", orderEntity.getOrderId(), delayMinutes);
        } catch (Exception e) {
            log.error("发送支付宝流程处理延时消息异常，订单ID: {}, 延时: {}分钟, 错误信息: {}", 
                    orderEntity != null ? orderEntity.getOrderId() : "null", delayMinutes, e.getMessage(), e);
            throw new RuntimeException("发送支付宝流程处理延时消息失败", e);
        }
    }

    /**
     * 发送带类型的支付宝流程处理消息（立即发送）
     * 
     * @param orderId 订单ID
     * @param messageType 消息类型
     */
    public void sendAlipayFlowMessage(Long orderId, String messageType) {
        try {
            log.info("发送支付宝流程处理消息，订单ID: {}, 类型: {}", orderId, messageType);
            rabbitMQUtil.sendMessage(
                RabbitMqQueueEnum.ALIPAY_FLOW.getQueueName(), 
                messageType, 
                orderId
            );
            log.info("支付宝流程处理消息发送成功，订单ID: {}, 类型: {}", orderId, messageType);
        } catch (Exception e) {
            log.error("发送支付宝流程处理消息异常，订单ID: {}, 类型: {}, 错误信息: {}", orderId, messageType, e.getMessage(), e);
            throw new RuntimeException("发送支付宝流程处理消息失败", e);
        }
    }

    /**
     * 发送带类型的支付宝流程处理消息（延时发送）
     * 
     * @param orderId 订单ID
     * @param messageType 消息类型
     * @param delay 延时时间
     * @param timeUnit 时间单位
     */
    public void sendAlipayFlowMessage(Long orderId, String messageType, long delay, TimeUnit timeUnit) {
        try {
            log.info("发送支付宝流程处理延时消息，订单ID: {}, 类型: {}, 延时: {}{}", 
                    orderId, messageType, delay, timeUnit.toString().toLowerCase());
            rabbitMQUtil.sendDelayMessage(
                RabbitMqQueueEnum.ALIPAY_FLOW.getQueueName(), 
                messageType, 
                orderId, 
                delay, 
                timeUnit
            );
            log.info("支付宝流程处理延时消息发送成功，订单ID: {}, 类型: {}, 延时: {}{}", 
                    orderId, messageType, delay, timeUnit.toString().toLowerCase());
        } catch (Exception e) {
            log.error("发送支付宝流程处理延时消息异常，订单ID: {}, 类型: {}, 延时: {}{}, 错误信息: {}", 
                    orderId, messageType, delay, timeUnit.toString().toLowerCase(), e.getMessage(), e);
            throw new RuntimeException("发送支付宝流程处理延时消息失败", e);
        }
    }

    /**
     * 发送支付宝流程重试消息
     * 
     * @param orderEntity 订单实体
     * @param retryCount 重试次数
     */
    public void sendAlipayFlowRetryMessage(OrderEntity orderEntity, int retryCount) {
        try {
            // 验证订单实体
            validateOrderEntity(orderEntity);
            
            log.info("发送支付宝流程重试消息，订单ID: {}, 重试次数: {}, 渠道: {}, 支付宝订单号: {}", 
                    orderEntity.getOrderId(), retryCount, orderEntity.getChannel(), orderEntity.getOrderCenterNo());
            
            String messageType = "ALIPAY_FLOW_RETRY_" + retryCount;
            // 重试延时递增：第1次延时30秒，第2次延时60秒，第3次延时120秒
            int delaySeconds = 30 * retryCount;
            rabbitMQUtil.sendDelayMessage(
                RabbitMqQueueEnum.ALIPAY_FLOW.getQueueName(), 
                messageType, 
                orderEntity.getOrderId(), 
                delaySeconds, 
                TimeUnit.SECONDS
            );
            log.info("支付宝流程重试消息发送成功，订单ID: {}, 重试次数: {}, 延时: {}秒", 
                    orderEntity.getOrderId(), retryCount, delaySeconds);
        } catch (Exception e) {
            log.error("发送支付宝流程重试消息异常，订单ID: {}, 重试次数: {}, 错误信息: {}", 
                    orderEntity != null ? orderEntity.getOrderId() : "null", retryCount, e.getMessage(), e);
            throw new RuntimeException("发送支付宝流程重试消息失败", e);
        }
    }

    /**
     * 验证订单实体
     * 
     * @param orderEntity 订单实体
     */
    private void validateOrderEntity(OrderEntity orderEntity) {
        if (orderEntity == null) {
            throw Ex.business("订单实体不能为空");
        }
        
        if (orderEntity.getOrderId() == null || orderEntity.getOrderId() <= 0) {
            throw Ex.business("订单ID无效");
        }
        
        if (!Objects.equal(orderEntity.getPlatform(), PlatformTypeEnum.ALIPAY.value())) {
            throw Ex.business("订单渠道{}不能同步，订单ID: {}",orderEntity.getPlatform(), orderEntity.getOrderId());
        }
        if (!Objects.equal(orderEntity.getPartnerId(), 100004L)) {
            throw Ex.business("渠道{}不能同步到支付宝，订单ID: {}",orderEntity.getPartnerId(), orderEntity.getOrderId());
        }
        
        if (Strings.isBlank(orderEntity.getOrderCenterNo())) {
            throw Ex.business("支付宝订单号(orderCenterNo)不能为空，订单ID: {}" , orderEntity.getOrderId());
        }
        if (Objects.equal(orderEntity.getOrderType(), OrderTypeEnum.DOOR_RECYCLE.value())) {
            throw Ex.business("上门订单不同步，订单ID: {}" , orderEntity.getOrderId());
        }
        
        log.debug("订单验证通过，订单ID: {}, 渠道: {}, 支付宝订单号: {}", 
                orderEntity.getOrderId(), orderEntity.getChannel(), orderEntity.getOrderCenterNo());
    }
}
